package com.hp.bon.sgw.wh.mml.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.bon.sgw.wh.mml.common.MMLSessionEntity;
import com.hp.bon.sgw.wh.mml.helper.HttpAckHelper;
import com.hp.bon.sgw.wh.mml.repositories.HttpResponseRepository;

public class HttpResponseHandler extends Thread {

	private static final Logger logger = LoggerFactory.getLogger(HttpResponseHandler.class);
	
	private boolean stop = false;
	
	private static HttpResponseHandler handler = null;
	
	public static void startHandler(){
		if(null==handler){
			handler = new HttpResponseHandler();			
		}
		handler.stop = false;
		handler.start();
	}
	
	public static void stopHandler(){
		handler.stop = true;
	}
	
	public static boolean isRunningHandler(){
		return handler.isAlive();
	}
	
	private HttpResponseHandler(){
		setDaemon(false);
	}
	
	@Override
	public void run() {
		logger.info("HttpResponseHandler is running...");
		while (true) {
			if (stop) {
				break;
			}
			MMLSessionEntity sessionEntity = HttpResponseRepository.poll();
			if (null == sessionEntity) {
				try {
					sleep(5000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} else {
				try {
					HttpAckHelper.doHttpAck(sessionEntity);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		logger.info("HttpResponseHandler is running...");
	}
	
}
